package com.user.exception;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.common.enums.error.ResultEnum;
import com.common.exception.StefanieException;
import com.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: stefanie-zy
 * @time: 2024/1/27-13:41
 * @description: 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class StefanieExceptionHandler {

    /**
     * 系统异常
     *
     * @return Result
     */
    @ExceptionHandler(StefanieException.class)
    public Result<?> handleSysException(StefanieException stefanieException) {
        log.error("{}：", stefanieException.getMessage());
        log.info("RESPONSE:{}", JSONUtil.toJsonStr(stefanieException));
        return Result.fail(stefanieException.getCode(), stefanieException.getMessage());
    }

    /**
     * Dto参数校验异常
     *
     * @param e 异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleValidationExceptions(MethodArgumentNotValidException e) {
        log.error("{}", e.getMessage());
        log.error("RESPONSE:{}", JSONUtil.toJsonStr(e));
        JSONObject errorMsg = new JSONObject();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            errorMsg.put(error.getField(), error.getDefaultMessage());
        }
        return Result.fail(ResultEnum.P_CHECK_ERROR.getCode(), ResultEnum.P_CHECK_ERROR.getMessage(), errorMsg);
    }
}
